"""
将未认领的产品入库
"""
from playwright.async_api import async_playwright

from utils.product_collector import ProductCollector


async def main(classify):
    p = await async_playwright().start()
    browser = await p.chromium.connect_over_cdp('http://localhost:9222')
    browser = browser.contexts[0]

    list_page = await browser.new_page()
    await list_page.goto('https://www.dianxiaomi.com/crawl/index.htm')

    # 切换到300条
    await list_page.locator('.page-up select[name="pageselct"]').select_option(value='300')

    pc = ProductCollector()

    # 获取产品
    pes = list_page.locator('#pageList .img-box a:not(.tb_btn)')
    for i in range(await pes.count()):
        pe = pes.nth(i)
        pel = await pe.get_attribute('href')
        try:
            await pc.add_product(pel, classify)
        except Exception as e:
            if str(e) == 'Product already exists':
                continue
            print(f'Error: {e}')



if __name__ == '__main__':
    import asyncio
    asyncio.run(main(1001))